package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.context.LoginUserContext;
import com.atguigu.lease.web.admin.service.SystemUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 用户访问系统逻辑之前 要求必须登录  校验token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头信息
        String token = request.getHeader("Access_token");

        if(!StringUtils.hasLength(token)){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        //2.解析token
        Long userId = JwtUtil.parseToken(token);
        SystemUser systemUser = systemUserService.getById(userId);
        systemUser.setPassword(null);

        //3.将数据保存到ThreadLocal中
        LoginUserContext.setUser(systemUser);

        //放行程序
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //返回数据前的最后一关
        LoginUserContext.removeUser();
    }
}
